package com.howard.base.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterConfig;

import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.howard.base.util.StringUtils;
//import com.opensymphony.xwork2.util.logging.Logger;
//import com.opensymphony.xwork2.util.logging.LoggerFactory;

@SuppressWarnings("deprecation")
public class BaseFilterDispatcher extends FilterDispatcher {

//    private static final Logger LOG = LoggerFactory.getLogger(BaseFilterDispatcher.class);

    @Override
    protected Dispatcher createDispatcher(FilterConfig filterConfig) {
        Map<String, String> params = new HashMap<String, String>();
        for (Enumeration<String> e = filterConfig.getInitParameterNames(); e.hasMoreElements();) {
            String name = e.nextElement();
            String value = filterConfig.getInitParameter(name);
            params.put(name, value);
        }
        this.scanStrutsXmlConfigurations(params);
        return new Dispatcher(filterConfig.getServletContext(), params);
    }

    private void scanStrutsXmlConfigurations(Map<String, String> params) {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath*:**/struts-*.xml";
        List<String> lstStrutsXml = new ArrayList<String>();
        lstStrutsXml.add("struts-default.xml");
        lstStrutsXml.add("struts-plugin.xml");
        lstStrutsXml.add("struts.xml");
        try {
            Resource[] resources = resolver.getResources(locationPattern);
            for (int i = 0; i < resources.length; i++) {
                lstStrutsXml.add(resources[i].getFile().getAbsolutePath());
            }
        } catch (IOException e) {
//            LOG.error("自动扫描加载Struts配置文件出错:" + e.getMessage(), e, new String[0]);
        }
        String configPaths = (String) params.get("config");
        if (configPaths != null) {
            String files[] = configPaths.split("\\s*[,]\\s*");
            for (int i = 0; i < files.length; i++) {
                if (StringUtils.isNotBlank(files[i]) && !lstStrutsXml.contains(files[i])) {
                    lstStrutsXml.add(files[i]);
                }
            }
        }
        configPaths = StringUtils.join(lstStrutsXml, ',');
        params.put("config", configPaths);
    }

}
